package gacha

import (
	"encoding/json"
	"errors"
	"io"
	"io/ioutil"
	"net/http"
	"net/url"
	"strconv"
	"strings"
	"time"
)

func load(domain string, query url.Values, ch *Ch) (result map[string][]GaCha, uid string, err error) {
	ch.sendMessage(`开始获取祈愿分类数据...`)
	config, err := getConfig(domain+`/event/gacha_info/api/getConfigList`, query)
	if err != nil {
		return nil, ``, err
	}
	if config.RetCode != 0 {
		return nil, ``, errors.New(config.Message)
	}
	m := []string{}
	for _, v := range config.Data.GachaTypeList {
		m = append(m, `[`+v.Name+`]`)
	}
	ch.sendMessage(`已获取到祈愿分类：` + strings.Join(m, `、`) + "，开始获取祈愿历史...")

	u := domain + `/event/gacha_info/api/getGachaLog`
	result = map[string][]GaCha{}
	for _, t := range config.Data.GachaTypeList {
		ids := map[string]bool{}
		list := []GaCha{}

		endId := `0`
		query.Set(`gacha_type`, t.Key)
		query.Set(`size`, `20`)
		n := 0
	tc:
		for {
			ch.sendMessage(`正在获取[` + t.Name + `]的第` + strconv.Itoa(n*20+1) + `至` + strconv.Itoa((n+1)*20) + `条数据...`)
			query.Set(`end_id`, endId)
			for i := 0; i < 5; i++ {
				gacha, err := getGaCha(u, query)
				if i == 5 && err != nil {
					return nil, ``, err
				}
				if err == nil {
					if len(gacha) == 0 {
						break tc
					}
					for _, g := range gacha {
						endId = g.Id
						if _, ok := ids[endId]; !ok {
							ids[endId] = true
							list = append(list, g)
						}
						if uid == `` && g.Uid != `` {
							uid = g.Uid
						}
					}
					break
				}
			}
			n++
			if n&7 == 0 {
				ch.sendMessage(`每加载8页休息1秒...`)
				time.Sleep(time.Second)
			}
		}

		if len(list) > 0 {
			result[t.Name] = list
		}
	}
	return result, uid, err
}

func getConfig(url string, query url.Values) (*Config, error) {
	body, err := get(url, query)
	if err != nil {
		return nil, err
	}
	data := &Config{}
	err = json.Unmarshal(body, data)
	if err != nil {
		return nil, err
	}
	return data, nil
}

func getGaCha(url string, query url.Values) ([]GaCha, error) {
	body, err := get(url, query)
	if err != nil {
		return nil, err
	}
	data := &JsonData{}
	err = json.Unmarshal(body, data)
	if err != nil {
		return nil, err
	}
	if data.RetCode != 0 {
		return nil, errors.New(data.Message)
	}
	return data.Data.List, nil
}

func get(url string, query url.Values) ([]byte, error) {
	req, err := http.NewRequest(`GET`, url, nil)
	if err != nil {
		return nil, err
	}
	req.URL.RawQuery = query.Encode()
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}
	defer func(Body io.ReadCloser) {
		_ = Body.Close()
	}(resp.Body)
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}
	return body, nil
}
